package com.itheima.interceptor;

import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求路径
        String uri = request.getRequestURI();
        log.info("uri={}", uri);
        //判断是否是登录请求
        if(uri.contains("login")) {
            //放行
            return true;
        }
        //获取token
        String token = request.getHeader("token");
        //判断token是否存在
        if(token==null){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //校验token
        try {
            Claims claims = JwtUtils.parseJWT(token);
            log.info("解析token成功:{}",claims);
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
        //放行
        return true;
    }
}
